﻿using System;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.GraphicsSystem;
using Autodesk.AutoCAD.Windows;

using gApp = Autodesk.AutoCAD.ApplicationServices.Application;
//using DBTransMan = Autodesk.AutoCAD.DatabaseServices.TransactionManager;
//using gDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiAcitveDocument;
using generic_class;
using my_database;

// 光配模块
namespace gp_class
{

    public struct _arraw_line_item
    {
        public Point2d ptStart;
        public Point2d ptEnd;
     //   bool solid; //标记实线还是虚线
    }

    //fiber太多，需要分表格显示  
    public enum _table_status
    {
        table_finished = 0,//一张表格处理完毕
        table_continue = 1//继续处理上次的表格
    }


    class module_gllxt
    {

        public int outNum = 0;
      //  public String m_dwgName;
   //     public String m_dwgStep;
    //    public String m_dwgNo;

        //整个表格的偏移位置
        public Point3d m_pOffset = new Point3d(100,100,0);
        //默认行高
        public double m_rowHeight = 3;
        //默认列宽度
        public double m_colWidth = 30;
        //默认标题字体大小
        public double m_fontHeaderWeight = 2 ;
        //正文字体大小
        public double m_fontWeight = 1;
        //默认表格间隙量
        public double tablesInter = 50;
        //表格偏移比例
        public double TableDxPrecent = 0.3;
        //所有光纤数
        public int m_nFiberNum = 0;
        //纤芯颜色数组
        string[] m_listColor = { "蓝", "橙", "绿", "棕 ", "灰", "本" };
        //光配
        string[] m_listRow = {"", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X","Y","Z" };

        MyDatabase m_connection =null;
        //不同屏柜表间距
        public int m_disTable = 150;
        //表格方向
        _direction m_direction = _direction.TABLE_HOR;

        //屏柜的每根fiber画一条线
        ArrayList m_lstArrawLine = null;
        //屏柜左侧向下的线
        ArrayList m_lstArrayLine2 = null;

        //屏柜线缆线间距
        public int m_disOffset = 30;
        //线y坐标间距，间隔不同线缆位置
        public int m_disDeleta = 5;
        //线宽
        public int m_nLineWidth = 5;
        //横线长度
        public int m_nWidthArraw = 100;
        /*画光缆联系表格*/

        private ArrayList m_lstFiber = null;

        public void DrawTable(string strName,int[] device,ProgressBar prg,int maxLines)
        {

            //新创建一个dwg文件
            DocumentCollection acDocMgr = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
            Document acDoc = acDocMgr.Add("");
            Database acCurDb = acDoc.Database;
            acDoc.LockDocument();

            // 启动一个事务  Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以只读方式打开块表   Open the Block table for read
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;

                // 以写方式打开模型空间块表记录   Open the Block table record Model space for write
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;

                //屏柜列表
                ArrayList lstTang = null;
                ArrayList lstTemp = null;
            /*     int[] device = new int[3];
               device[0] = 920;
               device[1] = 921;
               device[2] = 922;

                         device[0] = 749;
                             device[1] = 751;
                             device[2] = 734;
                             device[3] = 933;
              */

                //光缆最大纤芯36根，一张表的最大长度的最小值应该
                //大于36，否则会出现一张表容不下一个光缆的情况
                if (maxLines < 36)
                {
                    maxLines = 36;
                    MessageBox.Show("设定的最大行数的最小值应该大于最大纤芯数36");
                }

                lstTemp = m_connection.get_tang_from_device(device);

                //没有找到指定的设备，直接返回
                if ((lstTemp.Count == 0))
                {
                    System.Windows.Forms.MessageBox.Show("没有找到设备所属屏柜!");
                }

                //处理掉重复的屏柜
                lstTang = new ArrayList();
                for(int i=0;i< lstTemp.Count;i++)
                {
                    bool bFind = false;
                    tang_item item = (tang_item)lstTemp[i];
                    for (int j = 0; j < lstTang.Count; j++)
                    {
                        tang_item item_new = (tang_item)lstTang[j];
                        if (item_new.idtang == item.idtang)
                        {
                            bFind = true;
                            break;
                        }
                    }

                    if (false == bFind)
                        lstTang.Add(item);
                }

                //释放内存
                lstTemp = null;
                prg.Maximum = lstTang.Count;
                prg.Value = 0;
                _table_status lastStatus = _table_status.table_finished;
                //处理每一个屏柜
                for (int index = 0; index < lstTang.Count; )
                {
                    tang_item header = (tang_item)lstTang[index];
                    m_lstArrawLine = new ArrayList();
                    m_lstArrayLine2 = new ArrayList();

                    Table tbl = new Table();
                    tbl.TableStyle = acCurDb.Tablestyle;
                    tbl.NumRows = 3;
                    tbl.NumColumns =11;
                    // tbl.SetTextHeight(m_fontWeight);
                    tbl.SetColumnWidth(m_colWidth);
                    tbl.SetRowHeight(m_rowHeight);
                    lastStatus = DrawTangTable(tbl,header,maxLines);

                    if (_table_status.table_finished == lastStatus)
                    {
                        index++;
                        prg.Value++;
                        m_lstFiber = null;
                    }

                    // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                    acBlkTblRec.AppendEntity(tbl);
                    acTrans.AddNewlyCreatedDBObject(tbl, true);

                    //水平方向
                    if ((index > 0) || (_table_status.table_continue == lastStatus))
                    {
                        if (m_direction == _direction.TABLE_HOR)
                        {
                            m_pOffset += new Vector3d(m_disTable + tbl.Width, 0, 0);
                        }
                        else
                        {
                            m_pOffset += new Vector3d(0, m_disTable + tbl.Height, 0);
                        }
                    }
                    tbl.Position = m_pOffset;


                    //处理屏柜fiber 线缆
                    for (int i = 0; i < m_lstArrawLine.Count; i++)
                    {
                        _arraw_line_item item = (_arraw_line_item)m_lstArrawLine[i];
                        Line line = new Line();
                        line.StartPoint = new Point3d(item.ptStart.X + m_pOffset.X, item.ptStart.Y + m_pOffset.Y, 0);
                        line.EndPoint = new Point3d(item.ptEnd.X + m_pOffset.X, item.ptEnd.Y + m_pOffset.Y, 0);
                        line.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(0, 0, 255);

                        // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                        acBlkTblRec.AppendEntity(line);
                        acTrans.AddNewlyCreatedDBObject(line, true);

                    }


                    double nTableHeight = tbl.Height;
                    //处理屏柜fiber 线缆
                    for (int i = 0; i < m_lstArrayLine2.Count; i++)
                    {
                        _arraw_line_item item = (_arraw_line_item)m_lstArrayLine2[i];
                        Line line = new Line();
                        line.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(0, 0, 255);
                        line.StartPoint = new Point3d(item.ptStart.X + m_pOffset.X, item.ptStart.Y + m_pOffset.Y, 0);
                        line.EndPoint = new Point3d(item.ptEnd.X + m_pOffset.X, (-nTableHeight - 3*m_disDeleta) + m_pOffset.Y, 0);

                        // 添加新对象到块表记录和事务中   Add the new object to the block table record and the transaction
                        acBlkTblRec.AppendEntity(line);
                        acTrans.AddNewlyCreatedDBObject(line, true);
                    }

                    m_lstArrawLine = null;
                    m_lstArrayLine2 = null;

                }

                // 保存新对象到数据库中   Save the new object to the database
                acTrans.Commit();
            }

            acCurDb.SaveAs(strName, DwgVersion.Current);
        }


        /*画柜内配置表格*/
        private _table_status DrawTangTable(Table tbl,tang_item header,int maxLines)
        {
            //屏柜中光缆列表
            ArrayList lstFiber = null;
            //屏柜左侧的线的起始坐标
            Point2d ptStart = new Point2d(0, 0);

            int row_count = 3;
            int[] device= new int[1];
            device[0] = header.idtang;

            //获取屏柜fiber list
            if ((m_lstFiber != null) && (m_lstFiber.Count != 0))
                lstFiber = (ArrayList)m_lstFiber.Clone();
            else
                lstFiber = m_connection.get_cable_from_tang(device);

            //没有fiber
            if (lstFiber.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("没有找到屏柜光缆信息!");
                return _table_status.table_finished;
            }

            if (header.objectDesc == null)
                DrawTableHeader(tbl,"");
            else
                DrawTableHeader(tbl, header.objectDesc);

            //循环处理每一个fiber
            for (int i = 0; i < lstFiber.Count; i++)
            {
                int line_count = 0;
                int nIndex = 0;
                _arraw_line_item arrItem2 = new _arraw_line_item();
                cable_item itCalbe = (cable_item)lstFiber[i];
                int[] device1 = new int[1];
                device1[0] = itCalbe.idcable;
                ArrayList lstLine = m_connection.get_line_from_cable(device1);

                //如果超过了一张表格设定的最大行数，分表格显示
                if((row_count + lstLine.Count) > (maxLines + 3))
                {
                    int j = 0;
                    while (j <= (i-1))
                    {
                        lstFiber.RemoveAt(0);
                        j++;
                    }
                    m_lstFiber = (ArrayList)lstFiber.Clone();
                    return _table_status.table_continue;

                }

                //合并套管颜色的部分
                if (lstLine.Count > 0)
                {
                    //增加新的线缆行数
                    int temp_row_count = row_count;

                    //左侧的线，没一个fiber画完网左移动一个单位
                    ptStart = ptStart + new Vector2d(-m_disDeleta, 0);

                    //处理每个fiber中每条line
                    for (line_count = 0; line_count < lstLine.Count; line_count++)
                    {
                        double nHeight = 0;
                        Point2d tempStart;
                        Point2d tempEnd;
                        _arraw_line_item arrItem = new _arraw_line_item();
                        //计算线起始坐标,计算相对table的起始坐标系
                        //最后用table offset修正
                        tempStart = new Point2d(0, -tbl.Height);
                        ArrayList lstLineInfor = null;
                        //纤芯编号从1开始所以line_count + 1;
                        line_item itLine = (line_item)lstLine[line_count];
                        lstLineInfor = m_connection.get_line_info(itLine.idline , header.idtang);
                        tbl.InsertRows(row_count, m_rowHeight, 1);
                        for (int j = 0; j < lstLineInfor.Count; j++)
                        {
                            line_info line_infor = (line_info)lstLineInfor[j];
                            DrawRows(tbl, line_infor, row_count, line_count + 1);
                            row_count++;
                        }

                        //新增line后计算每条光缆占用的位置
                        tempEnd = new Point2d(0, -tbl.Height);

                        //ptStart,ptEnd,是每个单元个的起始坐标，最终需要计算中间点
                        nHeight = tempStart.Y - tempEnd.Y;
                        arrItem.ptStart = new Point2d(0,tempStart.Y - nHeight/2);
                        arrItem.ptEnd = new Point2d(ptStart.X, tempStart.Y - nHeight / 2);


                        //向下线只记录第一个line的y
                        if (0 == line_count)
                        {
                            arrItem2.ptStart = new Point2d(ptStart.X,arrItem.ptStart.Y);
                            //只记录x，y值根据所有表格画完后计算表格的高度获取
                            arrItem2.ptEnd = new Point2d(ptStart.X,0);

                            m_lstArrayLine2.Add(arrItem2);
                        }

                        m_lstArrawLine.Add(arrItem);
                    }


                    //处理套管颜色
                    line_count = lstLine.Count;
                    //每6根一种颜色
                    if (line_count <= 6)
                    {
                        tbl.MergeCells(new TableRegion(temp_row_count, 1, temp_row_count + lstLine.Count - 1, 1));
                        tbl.SetTextString(temp_row_count, 1, "本");
                    }
                    else
                    {
                        while (line_count > 6)
                        {
                            tbl.MergeCells(new TableRegion(temp_row_count + (nIndex * 6), 1, temp_row_count + (nIndex * 6) + 5, 1));
                            tbl.SetTextString(temp_row_count+(nIndex * 6), 1, m_listColor[nIndex % 6]);
                            nIndex++;
                            line_count -= 6;
                        }
                        if (line_count != 0)
                        {
                            tbl.MergeCells(new TableRegion(temp_row_count + (nIndex * 6), 1, temp_row_count + (nIndex * 6) + line_count - 1, 1));
                            tbl.SetTextString(temp_row_count + (nIndex * 6) , 1, m_listColor[nIndex % 6]);
                        }
                    }


                }

            }



             //统一处理屏柜每个fiber左侧的向下线
            for (int i = 0; i < m_lstArrayLine2.Count; i++)
            {
                _arraw_line_item temp = (_arraw_line_item)m_lstArrayLine2[i];
                temp.ptEnd = new Point2d(temp.ptStart.X, -tbl.Height - m_disDeleta);
            }

            return _table_status.table_finished;
        }


        //画表格头
        private void DrawTableHeader(Table tbl,String name)
        {

            tbl.MergeCells(new TableRegion(0,0,0,10));
            tbl.SetTextHeight(0, 0, m_fontHeaderWeight);
            tbl.SetAlignment(0, 0, CellAlignment.MiddleLeft);
            tbl.SetTextString(0, 0, name + "光配单元配线表");
            tbl.SetTextHeight(1, 0, m_fontHeaderWeight);
            tbl.SetTextString(1, 0, name + "光缆");

            tbl.MergeCells(new TableRegion(1, 0, 1, 2));
            tbl.MergeCells(new TableRegion(1, 4, 1, 6));
            tbl.MergeCells(new TableRegion(1, 3, 2, 3));
            tbl.MergeCells(new TableRegion(1, 7, 2, 7));
            tbl.MergeCells(new TableRegion(1, 8, 1, 10));

            tbl.SetTextHeight(m_fontHeaderWeight,3);
            tbl.SetTextString(2, 0, "纤芯序号");

          //  tbl.SetTextHeight(2, 1, m_fontHeaderWeight);
            tbl.SetTextString(2, 1, "套管颜色");
            tbl.SetTextString(2, 2, "光纤颜色");
            tbl.SetTextHeight(1,3,m_fontHeaderWeight);
            tbl.SetTextString(1, 3, "光配单元端子号");
            tbl.SetTextHeight(1, 4, m_fontHeaderWeight);
            tbl.SetTextString(1, 4, "柜内设备配线");

            tbl.SetTextString(2, 4, "尾纤/接口类型");
            tbl.SetTextString(2, 5, "装置名称");
            tbl.SetTextString(2, 6, "装置插件/端口号");
            tbl.SetTextHeight(1, 7, m_fontHeaderWeight);
            tbl.SetTextString(1, 7, "备注");
            
            tbl.SetTextHeight(1, 8, m_fontHeaderWeight);
            tbl.SetTextString(1, 8, "对侧装置");

            tbl.SetTextHeight(2, 8, m_fontHeaderWeight);
            tbl.SetTextString(2, 8, "装置名称");
            
            tbl.SetTextHeight(2, 9, m_fontHeaderWeight);
            tbl.SetTextString(2, 9, "接口类型");

            tbl.SetTextHeight(2, 10, m_fontHeaderWeight);
            tbl.SetTextString(2, 10, "插件端口号");
        }


        //画每行的数据
        private void DrawRows(Table tbl, line_info item, int rows, int line_count)
        {

            int index = (line_count -1) % m_listColor.Length;
            tbl.SetTextString(rows, 0, line_count.ToString());
            tbl.SetTextString(rows, 2, m_listColor[index]);
            if (null != item.gp_row)
            {
                int temp = Convert.ToInt32(item.gp_row);
                tbl.SetTextString(rows, 3, m_listRow[temp] + "-" + item.gp_col.ToString());
            }

            if (null != item.interface1)
            {
                tbl.SetTextString(rows, 4, item.interface1);
            }
            if (null != item.iedname1)
            {
                tbl.SetTextString(rows, 5, item.iedname1);
            }
            if (null != item.sendPortName)
            {
                tbl.SetTextString(rows, 6, item.sendPortName);
            }

            if (null != item.remark)
            {
                tbl.SetTextString(rows, 7, item.remark);
            }
            if (null != item.sendPortName)
            {
                tbl.SetTextString(rows, 8, item.sendPortName);
            }
            if (null != item.iedname2)
            {
                tbl.SetTextString(rows, 9, item.iedname2);
            }

            if (null != item.interface2)
            {
                tbl.SetTextString(rows, 10, item.interface2);
            }

            if (null != item.recvPort)
            {
                tbl.SetTextString(rows, 10, item.recvPort.ToString());
            }

        }

        public bool init(int scid)
        {
            m_connection = new MyDatabase();

            if (m_connection.init_connection(scid) == false)
            {
                System.Windows.Forms.MessageBox.Show("数据库初始化失败");
                return false;
            }

            return true;
        }

        public void close()
        {
            m_connection.close_connection();
        }

    }
}
